Skip to main content

242. Valid Anagram

Question

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

Constraints:

1 <= s.length, t.length <= 5 * 104
s and t consist of lowercase English letters.

Approach

  1. If two of the strings are not of equal length it will never be an anagram.
  2. First, iterate through the first string and put all the characters into a hash table with their count.
  3. Iterate the second string, and check against the map.
  4. If the character does not even exists in the map, it will never be an anagram too.
  5. If there is, decrease the count, and if it is 0, remove it from the map.
  6. An anagram will result in an empty map in the end. If it is not empty, it is not one.

Solution

class Solution {
public:
bool isAnagram(string s, string t) {
if(s.size() != t.size()) return false;

unordered_map<char,int> m;

for(int i = 0; i < s.size(); i++){
m[s[i]]++;
}

for(int k = 0; k < t.size(); k++){
if(m[t[k]]<= 0) return false;
m[t[k]] --;

if(m[t[k]] == 0) m.erase(t[k]);
}

return m.empty();
}
};